package org.wisteria.framework.web.mvc.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.LocaleResolver;
import org.wisteria.framework.web.APIResult;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import java.util.Locale;

@RestController
@RequestMapping("/framework/i18n")
@Api(value = "Wist框架国际化接口", tags = {"Wist框架接口"})
public class FrameworkI18NController {
    private static final Logger logger = LoggerFactory.getLogger(FrameworkI18NController.class);

    @Autowired
    private LocaleResolver localeResolver;

    @PostMapping("/locale")
    @ApiOperation("改变后端响应消息的默认语言")
    @Valid
    public APIResult<Boolean> changeLocale(HttpServletRequest request, HttpServletResponse response,
                                           /**
                                            * Spring 的请求Mapping时, 设置@RequestParam为true时, Spring抛出异常在前,
                                            * 不会再走到ControllerParameterValidationAspect
                                            * */
                                           @RequestParam(required = false)
                                           @NotNull String localeString,

                                           @RequestParam(required = false, defaultValue = "false") Boolean cookie
    ) {
        Locale locale = StringUtils.parseLocaleString(localeString);
        LocaleContextHolder.setLocale(locale);
        if (!cookie) {
            localeResolver.setLocale(request, response, locale);
        } else {
//            if (localeResolver instanceof RequestLocaleMixedResolver) {
//                ((RequestLocaleMixedResolver) localeResolver).setCookieLocale(request, response, locale);
//            } else {
//                return APIResponse.success(false);
//            }
        }
        return APIResult.success();
    }

    @GetMapping("/locale/context")
    @ApiOperation("改变后端响应消息的默认语言")
    public APIResult<String> getCurrentLocale() {
        return APIResult.success(LocaleContextHolder.getLocale().getLanguage());
    }
}
